package co.baiku.boot.wechat.config.mp;

import co.baiku.boot.wechat.enums.HttpClientType;
import co.baiku.boot.wechat.properties.WxMpProperties;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 微信公众号相关服务自动注册.
 *
 * @author someone
 */
@Configuration
@ConditionalOnProperty(prefix = "wx.mp", value = "enabled", havingValue = "true")
public class WxMpServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public WxMpService wxMpService(WxMpConfigStorage configStorage, WxMpProperties wxMpProperties) {
        HttpClientType httpClientType = wxMpProperties.getConfigStorage().getHttpClientType();
        WxMpService wxMpService;
        switch (httpClientType) {
            case HttpClient:
                wxMpService = newWxMpServiceHttpClientImpl();
                break;
            default:
                wxMpService = newWxMpServiceImpl();
                break;
        }

        wxMpService.setWxMpConfigStorage(configStorage);
        return wxMpService;
    }

    private WxMpService newWxMpServiceImpl() {
        return new WxMpServiceImpl();
    }

    private WxMpService newWxMpServiceHttpClientImpl() {
        return new WxMpServiceHttpClientImpl();
    }

}
